package com.spring.crm.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spring.crm.conf.CommonResult;
import com.spring.crm.conf.ResultCode;
import com.spring.crm.entity.SalesProcess;
import com.spring.crm.mapper.SalesProcessMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 何卓
 * @since 2022-01-10
 */
@RestController
@RequestMapping("/api/crm/sales-process")
public class SalesProcessController {
    @Resource
    private SalesProcessMapper salesProcessMapper;

    @CrossOrigin(origins = "*")
    @PostMapping("insert")
    public CommonResult insertOne(@RequestBody SalesProcess record) {
        CommonResult rs;
        try {
            if(record.getProcessName()==null){
                return CommonResult.failed("销售过程名称不能为空");
            }
            QueryWrapper<SalesProcess> queryWrapper = new QueryWrapper<>();
            Long count = salesProcessMapper.selectCount(queryWrapper);
            /*LocalDateTime dd = LocalDateTime.now(); // 注意是util包下的Date
            record.setCreateTime(dd);*/
            record.setProcessNum(Math.toIntExact(count));
            int ret = salesProcessMapper.insert(record);
            if (ret != 1){
                rs = CommonResult.failed();
            }else {
                JSONObject data = new JSONObject();
                data.put("salesProcessId",record.getSalesProcessId());
                rs = CommonResult.success(data);
            }
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
    @CrossOrigin(origins = "*")
    @GetMapping("condition")
    public CommonResult selectByCondition(@RequestParam Map<String,String> map) {
        CommonResult rs;
        try {
            QueryWrapper<SalesProcess> queryWrapper = new QueryWrapper<>();
            if(map.containsKey("salesProcessId")){
                queryWrapper.eq("sales_process_id",map.get("salesProcessId"));
            }
            queryWrapper.orderByAsc("process_num");
            Page<SalesProcess> page = new Page<>(Long.valueOf(map.get("current")),Long.valueOf(map.get("size")));
            IPage<SalesProcess> salesProcessIPage = salesProcessMapper.selectPage(page,queryWrapper);
            Integer selectCount = Math.toIntExact(salesProcessMapper.selectCount(queryWrapper));
            List<SalesProcess> list = salesProcessIPage.getRecords();
            rs = CommonResult.success(list,selectCount);
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @DeleteMapping ("delete")
    public CommonResult deleteOne(@RequestBody SalesProcess record) {
        CommonResult rs;
        try {
            SalesProcess salesProcess = salesProcessMapper.selectById(record.getSalesProcessId());
            if(salesProcess==null){
                return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
            }
            int ret = salesProcessMapper.deleteById(record.getSalesProcessId());
            if (ret != 1) {
                rs = CommonResult.failed();
            } else {
                rs = CommonResult.success("");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @PutMapping("update")
    public CommonResult updateOne(@RequestBody SalesProcess record) {
        CommonResult rs;
        try {
            SalesProcess salesProcess = salesProcessMapper.selectById(record.getSalesProcessId());
            if(salesProcess==null){
                return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
            }
            int ret = salesProcessMapper.updateById(record);
            if (ret != 1) {
                rs = CommonResult.failed();
            } else {
                JSONObject data = new JSONObject();
                data.put("salesProcessId", record.getSalesProcessId());
                rs = CommonResult.success(data);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @PostMapping("move")
    public CommonResult move(@RequestBody Map map) {
        CommonResult rs;
        try {
            //算法：先删除移动的过程，然后全部重新排号，并把它插进自己的位置（综合考虑后，采用了此算法，即使数据库数据有问题也会修正好）
            //最优算法：只修改以前位置到当前位置内的所有过程
            Integer newPlace = (Integer) map.get("newPlace");
            QueryWrapper<SalesProcess> queryWrapper = new QueryWrapper<>();
            Long count = salesProcessMapper.selectCount(queryWrapper);
            if(count < newPlace){
                return CommonResult.failed(ResultCode.REQ_DATA_ERROR);
            }
            String ThisId = (String) map.get("salesProcessId");
            SalesProcess ThisSalesProcess = salesProcessMapper.selectById(ThisId);
            ThisSalesProcess.setProcessNum(newPlace);
            salesProcessMapper.deleteById(ThisId);
            queryWrapper.orderByAsc("process_num");
            List<SalesProcess> list = salesProcessMapper.selectList(queryWrapper);
            Integer i = 0;
            for(SalesProcess salesProcess : list){
                if(i == newPlace){
                    salesProcessMapper.insert(ThisSalesProcess);
                    salesProcess.setProcessNum(i+1);
                    salesProcessMapper.updateById(salesProcess);
                } else if(i > newPlace){
                    salesProcess.setProcessNum(i+1);
                    salesProcessMapper.updateById(salesProcess);
                } else if(newPlace == list.size()){
                    salesProcess.setProcessNum(i);
                    salesProcessMapper.updateById(salesProcess);
                    if(list.size()-1 == i){
                        salesProcessMapper.insert(ThisSalesProcess);
                    }
                } else{
                    salesProcess.setProcessNum(i);
                    salesProcessMapper.updateById(salesProcess);
                }
                i++;

            }
            rs = CommonResult.success("");
        } catch (Exception ex) {
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
}
